/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.seari.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

/**
 *
 * @author Rainbow
 */
@Component
public class SpringContainer implements ApplicationContextAware
{
    private static ApplicationContext springContext;
    
    public static void initSpringContainer(String file)
    {	//springboot环境下不需要调用此方法手动初始化spring容器
        springContext = new ClassPathXmlApplicationContext(file);
        for (String beanDefinitionName : springContext.getBeanDefinitionNames())
        {
            System.out.println(beanDefinitionName);
        }
    }
    
    @Override
    public void setApplicationContext(ApplicationContext ac) throws BeansException
    {
        if(null == springContext)
        {
            springContext = ac;
        }
        System.out.println("========ApplicationContext配置成功,在普通类可以通过调用SpringContainer.getApplicationContext()获取applicationContext对象,applicationContext="+SpringContainer.springContext+"========");
    }
    
    //获取applicationContext  
    public static ApplicationContext getApplicationContext() {  
        return springContext;  
    }  
  
    //通过name获取 Bean.  
    public static Object getBean(String name){  
        return getApplicationContext().getBean(name);  
  
    }  
  
    //通过class获取Bean.  
    public static <T> T getBean(Class<T> clazz){  
        return getApplicationContext().getBean(clazz);  
    }  
  
    //通过name,以及Clazz返回指定的Bean  
    public static <T> T getBean(String name,Class<T> clazz){  
        return getApplicationContext().getBean(name, clazz);  
    }  
}
